package com.filter;


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class SSOFilter
  implements Filter
{

  private static final String defaultConfigFileName = "OAuth2-config.properties";
  private static Logger logger = LoggerFactory.getLogger(SSOFilter.class);
  private static String configFileName = "OAuth2-config.properties";
  private static String EXCEPT_PATTERNS = "";
  private FilterConfig fConfig;

  public static String getConfigFileName()
  {
    return configFileName;
  }

  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {

      return;
    
  }

  public void init(FilterConfig filterConfig)
    throws ServletException
  {
    this.fConfig = filterConfig;
    try {
      configFileName = filterConfig.getInitParameter("configFileName");
      if ((configFileName == null) || (configFileName.equals(""))) {
        configFileName = "OAuth2-config.properties";
      }
     // this.config = new OAuth2Config(configFileName);
      EXCEPT_PATTERNS = filterConfig.getInitParameter("_except_urlpattern");
    } catch (Exception e) {
      e.printStackTrace();
      throw new ServletException(e);
    }
  }

  private void error(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    response.addHeader("Cache-Control", "no-store");
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Content-Type", "application/json;charset=UTF-8");
    response.setStatus(401);
    response.getWriter().print("{\"resultcode\":401 ,\"error\":\"Invalid token\"}");
  }

  private Boolean isAjaxRequest(HttpServletRequest request, HttpServletResponse response)
  {
    String requestWith = request.getHeader("X-Requested-With");
    String accessHeader = request.getHeader("X-Access-Method");
    if ((accessHeader != null) && ("mobileLogin".equalsIgnoreCase(accessHeader))) {
      return Boolean.valueOf(true);
    }
    if ((StringUtils.isEmpty(requestWith)) && ("XMLHttpRequest".equalsIgnoreCase(requestWith))) {
      if ((accessHeader != null) && ("ajaxLogin".equalsIgnoreCase(accessHeader))) {
        return Boolean.valueOf(false);
      }
      return Boolean.valueOf(true);
    }
    return Boolean.valueOf(false);
  }
}